package com.tehui.activity.impl;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.tehui.R;
import com.tehui.activity.BaseActivity;
import com.tehui.utils.ui.UiUtils;
import com.tencent.connect.auth.QQAuth;
import com.tencent.open.wpa.WPA;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

//客服
public class ServiceActivity extends BaseActivity {

    @BindView(R.id.tvQQ)
    TextView tvQQ;
    @BindView(R.id.tvWeiX)
    TextView tvWeiX;
    @BindView(R.id.tvNum)
    TextView tvNum;
    private View      view;
    private Dialog    dialog;
    private String    qq;
    private String    tel;
    private String    wx;
    private String    wxImg;
    private ImageView imageView;

    @Override
    public void initActivityData() {
        super.initActivityData();
        tvTitle.setText("联系客服");
        getServre();
        init();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_service;
    }

    @OnClick({R.id.tencent, R.id.wechat, R.id.phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tencent:
                if (!TextUtils.isEmpty(qq)) {
                    tencentService();
                }
                break;
            case R.id.wechat:
                dialog.show();
                Glide.with(ServiceActivity.this).asBitmap().load(wxImg).into(imageView);
                break;
            case R.id.phone:
                if (!TextUtils.isEmpty(tel)) {
                    call();
                }
                break;
        }
    }

    private void getServre() {
        OkGo.get("http://dl.21tehui.com/AppContactApi.html").tag(this).cacheKey("cacheKey").cacheMode
                (CacheMode.DEFAULT).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (s != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        qq = jsonObject.optString("qq");
                        tel = jsonObject.optString("tel");
                        wx = jsonObject.optString("wx");
                        wxImg = jsonObject.optString("wxImg");

                        tvQQ.setText("客服QQ:\n" + qq);
                        tvNum.setText("客服电话:\n" + tel);
                        tvWeiX.setText("客服微信:\n" + wx);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void init() {
        //大图所依附的dialog
        dialog = new Dialog(ServiceActivity.this, R.style.NobackDialog_two);
        view = View.inflate(UiUtils.getContext(), R.layout.service_img_layout, null);
        dialog.setContentView(view);
        imageView = (ImageView) view.findViewById(R.id.image);

        //大图的点击消失
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        //大图的长按监听
        imageView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                //弹出的“保存图片”的Dialog
                final AlertDialog.Builder builder = new AlertDialog.Builder(ServiceActivity.this);
                builder.setItems(new String[]{getResources().getString(R.string.save_picture)}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        saveCroppedImage(((BitmapDrawable) imageView.getDrawable()).getBitmap());
                    }
                });
                builder.show();
                return true;
            }
        });
    }

    //保存图片
    private void saveCroppedImage(Bitmap bmp) {
        File file = new File("/sdcard/21tehui");
        if (!file.exists()) {
            file.mkdir();
        }

        file = new File("/sdcard/temp.jpg".trim());
        String fileName = file.getName();
        String mName = fileName.substring(0, fileName.lastIndexOf("."));
        String sName = fileName.substring(fileName.lastIndexOf("."));

        // /sdcard/myFolder/temp_cropped.jpg
        String newFilePath = "/sdcard/21tehui" + "/" + mName + "_cropped" + sName;
        file = new File(newFilePath);
        try {
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 50, fos);
            fos.flush();
            fos.close();
            UiUtils.toast("保存成功");
            galleryAddPic(this, newFilePath);
        } catch (IOException e) {
            e.printStackTrace();
            UiUtils.toast("保存失败");
        }
    }

    //刷新图库
    public static void galleryAddPic(Context context, String path) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(path);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        context.sendBroadcast(mediaScanIntent);
    }

    //QQ客服
    private void tencentService() {
        QQAuth mqqAuth = QQAuth.createInstance("1106026080", this); // 你申请的APP_ID,mContext是上下文
        WPA mWPA = new WPA(this, mqqAuth.getQQToken());
        int ret = mWPA.startWPAConversation(this, qq, ""); //客服QQ
        if (ret != 0) { //如果ret不为0，就说明调用SDK出现了错误
            UiUtils.toast("抱歉，联系客服出现了错误~");
        }
    }

    //电话
    private void call() {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        jumpToActivity(intent);
    }
}
